package com.duanjw.java.mysql;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    public List<User> select(){
        List users = new ArrayList<User>();
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            Connection connection = DBUtil.getConnection();
            statement = connection.createStatement();
            resultSet = statement.executeQuery("select * from user");
            while (resultSet.next()){
                User user = new User();
                user.setId(resultSet.getInt(1));
                user.setName(resultSet.getString(2));
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                resultSet.close();
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return users;
    }
    public boolean insert(){
        Statement statement = null;
        Boolean flag = null;
        try {
            Connection connection = DBUtil.getConnection();
            statement = connection.createStatement();
            flag = statement.execute("insert into user values (1,'张')");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }
    public boolean delete(){
        Statement statement = null;
        Boolean flag = null;
        try {
            Connection connection = DBUtil.getConnection();
            statement = connection.createStatement();
            flag = statement.execute("delete from user");
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        new UserDao().delete();
        new UserDao().insert();
        new UserDao().select().forEach(System.out::print);
    }
}
